package org.depsea.oss.client.aliyun;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.depsea.oss.client.CustomerBucketPresignedUrlGenerator;
import org.depsea.oss.client.PresignedUrlGenerator;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class AliyunPresignedUrlGenerator implements PresignedUrlGenerator {

    private final OSSClient ossClient;
    private final String defaultBucketName;

    @Setter
    private Long expirationSecond;

    public AliyunPresignedUrlGenerator(OSSClient ossClient, String defaultBucketName) {
        this.ossClient = ossClient;
        this.defaultBucketName = defaultBucketName;
        this.expirationSecond = TimeUnit.MINUTES.toSeconds(15);
    }

    @Override
    public String generate(String fullPath) {
        return this.generateByBucket(defaultBucketName, fullPath);
    }

    @Override
    public String generateByBucket(String bucketName, String fullPath) {
        Date expiration = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(this.expirationSecond));
        // 生成以GET方法访问的预签名URL。本示例没有额外请求头，其他人可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, fullPath, expiration);
        return url.toString();
    }

    @Override
    public String generateWithArguments(String fullPath, Map<String, String> arguments) {
        return this.generateByBucketWithArguments(defaultBucketName, fullPath, arguments);
    }

    @Override
    public String generateByBucketWithArguments(String bucketName, String fullPath, Map<String, String> arguments) {
        Date expiration = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(this.expirationSecond));
        GeneratePresignedUrlRequest presignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, fullPath);
        presignedUrlRequest.setExpiration(expiration);
        presignedUrlRequest.setMethod(HttpMethod.GET);
        if (arguments != null && arguments.containsKey("x-oss-process")) {
            presignedUrlRequest.setProcess(arguments.get("x-oss-process"));
        }

        if (arguments != null) {
            Map<String, String> params = new HashMap<>(arguments);
            params.remove("x-oss-process");
            presignedUrlRequest.setQueryParameter(params);
        }

        URL url = ossClient.generatePresignedUrl(presignedUrlRequest);
        return url.toString();
    }


}
